package com.skyworth.web.admin.category.service.impl;

import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.skyworth.web.admin.category.domain.CategoryModel;
import com.skyworth.web.admin.category.form.CategoryForm;
import com.skyworth.web.admin.category.repository.CategoryRepository;
import com.skyworth.web.admin.category.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by skyworth on 2016/8/8.
 */
@Service
public class CategoryServiceImpl implements CategoryService {

	@Autowired
	private CategoryRepository categoryRepository;

	@Override
	public CategoryModel addCategory(CategoryForm categoryForm) {
		CategoryModel categoryModel = new CategoryModel();
		categoryModel.name = categoryForm.name;
		categoryModel.storeId = categoryForm.storeId;
		categoryRepository.save(categoryModel);
		return categoryModel;
	}

	@Override
	public void delCategory(long id) {
//		categoryRepository.delete(id);
		categoryRepository.del(id);
	}

	@Override
	public CategoryModel updateCategory(CategoryForm menuForm) {
		CategoryModel categoryModel = categoryRepository.findOne(menuForm.id);
		categoryModel.name = menuForm.name;
		categoryRepository.save(categoryModel);
		return categoryModel;
	}

	@Override
	public CategoryModel findCategory(long id) {
		return categoryRepository.findOne(id);
	}

	@Override
	public boolean existCategoryByName(String name, long store_id) {
		return categoryRepository.existByName(name, store_id);
	}

	@Override
	public boolean existCategory(String name, long id, long store_id) {
		return categoryRepository.existCategory(name, id, store_id);
	}



	@Override
	public List<CategoryModel> listCategory(JsonObject params) {
		if(params != null){
			long storeId = params.get("store_id").getAsLong();
			return Lists.newArrayList(categoryRepository.findByStoreId(storeId));
		}
		return Lists.newArrayList(categoryRepository.findAll());
	}

	@Override
	public List<CategoryModel> listCategoryByStore(long store_id) {
		return Lists.newArrayList(categoryRepository.findByStoreId(store_id));
	}

	@Override
	public Page<CategoryModel> pageCategory(JsonObject params, Pageable pageable) {

		if(params != null){
			long storeId = params.get("store_id").getAsLong();
			return categoryRepository.getCategoryByStoreId(storeId, pageable);
		}
		return categoryRepository.allValidCategory(pageable);
	}

	@Override
	public Iterable<CategoryModel> findCategoryByStoreId(long storeId) {
		return categoryRepository.findByStoreId(storeId);
	}
}
